package com.system.borrow.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.system.borrow.Constant.URLDefind;
import com.system.borrow.R;
import com.system.borrow.bean.CustomerDTO;
import com.system.borrow.bean.GloData;
import com.system.borrow.callback.DialogCallback;
import com.system.borrow.fragment.MyFragment;
import com.system.borrow.http.model.HttpParams;
import com.system.borrow.http.utils.OkHttpUtils;
import com.system.borrow.utils.SecondTitle;
import com.system.borrow.utils.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 注册
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    EditText et_mobile, et_pwd, et_code;
    TextView tv_code;
    Button btn_register;
    private TimeCount time;
    private ImageView iv_password;
    boolean isSeePass = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        SecondTitle title = new SecondTitle(this);
        title.setTitle("注册", null);
        time = new TimeCount(60000, 1000);
        initView();
        initListener();
    }

    private void initListener() {
        btn_register.setOnClickListener(this);
        tv_code.setOnClickListener(this);
        iv_password.setOnClickListener(this);
    }

    private void initView() {
        et_mobile = (EditText) findViewById(R.id.et_mobile);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_code = (EditText) findViewById(R.id.et_code);
        tv_code = (TextView) findViewById(R.id.tv_code);
        btn_register = (Button) findViewById(R.id.btn_register);
        iv_password = (ImageView) findViewById(R.id.iv_password);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_register:
                if (et_mobile.getText().toString().length() == 0) {
                    ToastShow("请输入手机号码");
                } else if (et_pwd.getText().toString().length() == 0) {
                    ToastShow("请输入密码");
                } else if (et_code.getText().toString().length() == 0) {
                    ToastShow("请输入验证码");
                } else {
                    register(et_mobile.getText().toString().trim(), et_pwd.getText().toString().trim(), et_code.getText().toString().trim());
                }
                break;
            case R.id.tv_code:
                if (et_mobile.getText().toString().length() == 0) {
                    ToastShow("请输入手机号码");
                } else {
                    time.start();// 开始计时
                    getCode();
                }
                break;
            case R.id.iv_password:
                if (!isSeePass) {
                    et_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    isSeePass = true;
                } else {
                    isSeePass = false;
                    et_pwd.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                break;
        }
    }

    /**
     * 注册
     *
     * @param mobile
     * @param password
     * @param code
     */
    private void register(String mobile, String password, String code) {
        HttpParams params = new HttpParams();
        params.put("mobile", mobile);
        params.put("password", password);
        params.put("code", code);
        OkHttpUtils.post(URLDefind.REGISTER)
                .tag(this)
                .params(params)
                .execute(new DialogCallback<String>(this, String.class, null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            int statusCode = jsonObject.getInt("statusCode");
                            Gson gson = new Gson();
                            if (statusCode == 200) {
                                String data = jsonObject.getString("data");
                                TypeToken<CustomerDTO> token = new TypeToken<CustomerDTO>() {
                                };
                                CustomerDTO customer = gson.fromJson(data, token.getType());
                                GloData.setCustomerDTO(customer);
                                if(MyFragment.myFragment!=null){
                                    MyFragment.myFragment.loadData();
                                }
                                SharedPreferencesUtil.putString(RegisterActivity.this,"custormer","custormer",gson.toJson(customer));
                                ToastShow("恭喜您,注册成功");
                                finish();
                            } else {
                                ToastShow(jsonObject.getString("message"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }

    /**
     * 获取验证码
     */
    private void getCode() {
        HttpParams params = new HttpParams();
        params.put("mobile", et_mobile.getText().toString());
        params.put("type", "1");
        OkHttpUtils.post(URLDefind.SEND_CODE)
                .params(params)
                .tag(this)
                .execute(new DialogCallback<String>(this, String.class, null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject json = new JSONObject(s);
                            int statusCode = json.getInt("statusCode");
                            if (statusCode == 200) {
                                ToastShow("短信已发送,请注意查收");
                            } else {
                                time.onFinish();
                                ToastShow(json.getString("message"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        ToastShow("网络异常");
                    }
                });
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            tv_code.setText("获取");
            tv_code.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            tv_code.setClickable(false);//防止重复点击
            tv_code.setText(millisUntilFinished / 1000 + "s");
        }
    }
}
